package main

import (
	"context"
	"gitee.com/bei_yi_ning/gorder/common/broker"
	_ "gitee.com/bei_yi_ning/gorder/common/config"
	"gitee.com/bei_yi_ning/gorder/common/logging"
	"gitee.com/bei_yi_ning/gorder/common/server"
	"gitee.com/bei_yi_ning/gorder/common/tracing"
	"gitee.com/bei_yi_ning/gorder/payment/infra/consumer"
	"gitee.com/bei_yi_ning/gorder/payment/service"
	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
)

func init() {
	logging.Init()
}

func main() {
	serviceName := viper.GetString("payment.service-name")
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	serverType := viper.GetString("payment.server-to-run")

	// 实例化opentelemetry
	shutdown, err := tracing.InitJaegerProvider(viper.GetString("jaeger.url"), serviceName)
	if err != nil {
		logrus.Fatal(err)
	}
	defer shutdown(ctx)
	//

	application, cleanup := service.NewApplication(ctx) // 拥有创建订单的服务能力
	defer cleanup()

	// connect to mq
	ch, closeCh := broker.Connect(
		viper.GetString("rabbitmq.user"),
		viper.GetString("rabbitmq.password"),
		viper.GetString("rabbitmq.host"),
		viper.GetString("rabbitmq.port"),
	)
	defer func() {
		_ = closeCh()
		_ = ch.Close()
	}()

	go consumer.NewConsumer(application).Listen(ch)
	paymentHandler := NewPaymentHandler(ch)
	switch serverType {
	case "http":
		server.RunHTTPServer(serviceName, paymentHandler.RegisterRoutes)
	case "grpc":
		logrus.Panic("unsupported server type : grpc")
	default:

		logrus.Panicf("unsupported server type :%s", serverType)
	}

}

// panic和fatal的区别：
// panic相当于一个异常，如果你可以正常recover的话，随着调用栈可以一路往上冒 他会一层一层调用栈执行defer函数 直到main函数
// fatal直接挂掉整个进程  什么都不会做
